﻿using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;

namespace Utils
{
    public class FileTools
    {
        public static bool FileExists(string path)
        {
            if (File.Exists(Directory.GetCurrentDirectory() + "\\" + path))
            {
                return true;
            }
            return false;
        }
        public static bool FolderExists(string path)
        {
            if (!System.IO.Directory.Exists(Directory.GetCurrentDirectory() + "\\" + path))
            { return true; }
            return false;
        }
        public static string ReadFile(string path)
        {
            path = Directory.GetCurrentDirectory() + "\\" + path;
            string result = "";
            try
            {
                using (StreamReader sr = new StreamReader(path))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        result += line+Environment.NewLine;
                    }
                }
            }
            catch (Exception e)
            {
            }
            return result;
        }

        public static void WriteFile(string text, string path)
        {
            string filePath = Directory.GetCurrentDirectory() + "\\" + path;
            if (File.Exists(filePath))
                File.Delete(filePath);
            try
            {
                System.IO.File.WriteAllText(filePath, text);
            }
            catch (Exception ex)
            {

            }
        }
        public static byte[] GetBytes(string str)
        {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
            return bytes;
        }

        public static string Utf8ToString(IntPtr aUtf8)
        {
            if (aUtf8 == IntPtr.Zero)
                return null;
            int len = 0;
            while (Marshal.ReadByte(aUtf8, len) != 0)
                len++;
            if (len == 0)
                return "";
            byte[] array = new byte[len];
            Marshal.Copy(aUtf8, array, 0, len);
            return Encoding.UTF8.GetString(array);
        }
    }
}
